package com.common.test;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

import com.common.util.RunSettingUtil;
import com.common.util.WebDriverUtil;

	/**
		@author 王嘉犇
		@name UI测试基类
	 */

public class UITestBase extends TestBase {
	
	public WebDriver driver;
	
	private String windowhandlepresent = "";
	
    public WebDriver getDriver() {
        return driver;
    }
    
    @BeforeClass
    public void beforeclass() throws Exception {
        log.info("===============BeforeClass===============");
        KillProcess.killprocess();
        log.info("init Driver");
        driver = WebDriverUtil.initWebDriver();
    }

    @AfterClass
    public void afterclass() {
    	driver.quit();
        log.info("===============AfterClass===============");
    }
    
    /**
     * 在未打开任何一个页面的情况下，打开一个新页面，参数为url地址
     */
    public void openurl(String url) {
    	driver.manage().timeouts().pageLoadTimeout(RunSettingUtil.WAITTIME, TimeUnit.SECONDS);
        driver.navigate().to(url);
    }

    /**
     * 打开一个新页面，参数为url地址和用户cookie
     */
    public void openurlWithCookie(String url, Cookie ck) {
        driver.navigate().to(url);
        driver.manage().addCookie(ck);
    }

    /**
     * 在已经有打开页面的情况下，打开一个新页面，参数为url地址
     */
    public void opennewwindow(String url) {
        JavascriptExecutor executor = (JavascriptExecutor) driver;
        executor.executeScript("window.open('" + url + "')");
    }

    /**
     * 记录当前窗口的句柄
     */
    public void recordWindowHandle() {
        windowhandlepresent = driver.getWindowHandle();
    }

    /**
     * 切换窗口
     */
    public void switchTonewWindow() {
        Set<String> windowhandles = driver.getWindowHandles();
        for (String windowhandle : windowhandles) {
            if (windowhandle.equals(windowhandlepresent)) {
                continue;
            } else {
                driver.switchTo().window(windowhandle);
                break;
            }
        }
    }
}
